package org.zlb.netty.client.rpc;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.zlb.netty.dbo.RpcRequest;
import org.zlb.netty.dbo.RpcResponse;
import org.zlb.netty.server.rpc.RpcMessageDecode;
import org.zlb.netty.server.rpc.RpcMessageEncode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

public class RpcMessageClient {
    
    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    
    private String host = null;
    private int port = -1;
    private RpcMessageClientHandler handler;
    private Channel channel;
    private ReentrantLock lock = new ReentrantLock();
    private Condition connect = lock.newCondition();
    
    
    public RpcMessageClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    
    public void connect() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    ch.pipeline().addLast(new RpcMessageDecode(RpcResponse.class));
                    ch.pipeline().addLast(new LengthFieldPrepender(4));
                    ch.pipeline().addLast(new RpcMessageEncode());
                    ch.pipeline().addLast(new RpcMessageClientHandler());
                }
            });
            
            ChannelFuture f = b.connect(this.host, this.port).sync();
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                        handler = future.channel().pipeline().get(RpcMessageClientHandler.class);
                        lock.lock();
                        connect.signal();
                        lock.unlock();
                    }
                }
            });
            
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接服务端失败");
        } finally {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                        connect();
                    } catch (InterruptedException e) {
                         e.printStackTrace();
                    }
                }
            });
        }
    }
    
    public RpcResponse sendRequest(RpcRequest req) throws InterruptedException {
        lock.lock();
        if (this.channel == null) {
            connect.await();
        }
        lock.unlock();
        handler.send(this, req);
        
        return handler.response(req);
    }
    
}
